import router from '@/router'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { localCache, sessionCache } from '@/utils/storage'
import { IAccount, loginRequest, getUserInfoById, getUserRouterList } from '@/service/login/login'
import { mapMenusToRoutes } from '@/utils/mapRouters'

interface ILoginState {
	token: string
	userInfo: any
	userRouters: any[]
	headerTags: any[]
}

export const useLoginStore = defineStore('login', {
	state(): ILoginState {
		return {
			token: '',
			userInfo: {},
			userRouters: [],
			headerTags: []
		}
	},
	actions: {
		async accountLoginAction(payload: IAccount) {
			const { id, token } = await loginRequest(payload)
			this.token = token
			localCache.setItem('token', token)

			const userInfo = await getUserInfoById({ id })
			this.userInfo = userInfo
			localCache.setItem('userInfo', userInfo)

			const userRouters = await getUserRouterList({ id })
			this.userRouters = userRouters
			this.registerRouters(userRouters)
			localCache.setItem('userRouters', userRouters)

			ElMessage.success('登录成功')
			router.push('/main')
		},

		registerRouters(menus: any[]) {
			const routes = mapMenusToRoutes(menus)
			routes.forEach((route) => {
				router.addRoute('main', route)
			})
		},

		loadLocalStorage() {
			const token = localCache.getItem('token')
			if (token) {
				this.token = token
			}

			const userInfo = localCache.getItem('userInfo')
			if (userInfo) {
				this.userInfo = userInfo
			}

			const userRouters = localCache.getItem('userRouters')
			if (userRouters) {
				this.userRouters = userRouters
				this.registerRouters(userRouters)
			}

			// 取出缓存的tags
			const headerTags = sessionCache.getItem('headerTags')
			if (headerTags) {
				this.headerTags = headerTags
			}
		},

		addRouteToTags(route: any) {
			const tag = {
				label: route.meta.title,
				path: route.path
			}
			this.headerTags.push(tag)
		}
	}
})

export function setupStore() {
	const loginStore = useLoginStore()
	loginStore.loadLocalStorage()
}
